#include "network_api_handler.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
#include <regex>
#include <chrono>
#include "base_log.h"
#include "system_server.h"
#include "web_server.h"
#include "common_config_manager.h"

namespace El {
namespace Restful {

// 获取网络配置的HTTP处理函数
WebServer::HttpResponse HandleGetNetworkConfig(const WebServer::HttpRequest &req)
{
    WebServer::HttpResponse response;
    response.content_type = "application/json";

    // 解析请求体为JSON (如果有)
    nlohmann::json request_json;
    if (!req.body.empty()) {
        // 使用条件判断替代异常处理
        nlohmann::json parsed = nlohmann::json::parse(req.body, nullptr, false);
        if (parsed.is_discarded()) {
            LOG_ERROR("解析请求JSON失败");
            response.status_code = 400;
            nlohmann::json error = {{"code", 400},
                                    {"message", "Invalid JSON format"},
                                    {"data", nullptr},
                                    {"error", "Failed to parse request JSON"}};
            response.body = error.dump();
            return response;
        }
        request_json["body"] = parsed;
    }

    // 调用JSON处理函数
    nlohmann::json response_json;
    bool success = GetNetworkConfigHandler(request_json, response_json);

    // 设置HTTP状态码和响应体
    response.status_code = response_json.contains("code") ? response_json["code"].get<int>() : (success ? 200 : 500);
    response.body = response_json.dump();

    return response;
}

// 提取接口名称参数的HTTP处理函数
WebServer::HttpResponse HandleUpdateInterfaceConfig(const WebServer::HttpRequest &req)
{
    WebServer::HttpResponse response;
    response.content_type = "application/json";

    // 使用正则表达式从URI中提取接口名称
    std::regex pattern("^/v1/network/interfaces/([^/]+)$");
    std::smatch matches;
    if (!std::regex_match(req.uri, matches, pattern) || matches.size() != 2) {
        LOG_ERROR("无效的URI格式: 缺少接口名称");
        response.status_code = 400;
        nlohmann::json error = {{"code", 400},
                                {"message", "Bad Request"},
                                {"data", nullptr},
                                {"error", "Invalid URI format: missing interface name"}};
        response.body = error.dump();
        return response;
    }

    std::string interface_name = matches[1].str();

    // 创建包含接口名称的请求
    nlohmann::json request_json;
    if (!req.body.empty()) {
        // 使用条件判断替代异常处理
        nlohmann::json parsed = nlohmann::json::parse(req.body, nullptr, false);
        if (parsed.is_discarded()) {
            LOG_ERROR("解析请求JSON失败");
            response.status_code = 400;
            nlohmann::json error = {{"code", 400},
                                    {"message", "Invalid JSON format"},
                                    {"data", nullptr},
                                    {"error", "Failed to parse request JSON"}};
            response.body = error.dump();
            return response;
        }
        request_json["body"] = parsed;
    }

    request_json["params"] = nlohmann::json::object();
    request_json["params"]["interface_name"] = interface_name;

    // 调用处理函数
    nlohmann::json response_json;
    bool success = UpdateInterfaceConfigHandler(request_json, response_json, interface_name);

    // 创建HTTP响应
    response.status_code = response_json.contains("code") ? response_json["code"].get<int>() : (success ? 200 : 500);
    response.body = response_json.dump();
    return response;
}

bool GetNetworkConfigHandler(const nlohmann::json &request, nlohmann::json &response)
{
    (void)request; // 未使用参数

    try {
        // 从ConfigManager获取网络配置
        auto &configManager = El::Common::ConfigManager::GetInstance();
        nlohmann::json networkConfig = configManager.GetConfig("network");

        // 构建响应
        response["code"] = 200;
        response["message"] = "OK";
        response["data"] = networkConfig;
        response["error"] = nullptr;

        return true;
    } catch (const std::exception &e) {
        // 处理异常
        LOG_ERROR("获取网络配置失败: {}", e.what());
        response["code"] = 500;
        response["message"] = "Internal Server Error";
        response["data"] = nullptr;
        response["error"] = "Failed to get network configuration";
        return false;
    }
}

bool UpdateInterfaceConfigHandler(const nlohmann::json &request,
                                nlohmann::json &response,
                                const std::string &interface_name)
{
    // 检查请求体是否包含必要字段
    if (!request.contains("body")) {
        response["code"] = 400;
        response["message"] = "Bad Request";
        response["data"] = nullptr;
        response["error"] = "Request body is required";
        return false;
    }

    const auto &body = request["body"];

    try {
        auto &systemServer = El::SystemServer::SystemServer::GetInstance();
        bool success = true;
        std::string errorMsg;

        // 更新网络配置
        if (body.contains("mode")) {
            std::string mode = body["mode"].get<std::string>();

            if (mode == "static") {
                // 检查静态IP配置所需的字段
                if (!body.contains("ipv4") || 
                    !body["ipv4"].contains("address") || 
                    !body["ipv4"].contains("netmask") || 
                    !body["ipv4"].contains("gateway")) {
                    response["code"] = 400;
                    response["message"] = "Bad Request";
                    response["data"] = nullptr;
                    response["error"] = "Missing required fields for static IP configuration";
                    return false;
                }

                std::string address = body["ipv4"]["address"].get<std::string>();
                std::string netmask = body["ipv4"]["netmask"].get<std::string>();
                std::string gateway = body["ipv4"]["gateway"].get<std::string>();

                if (!systemServer.ConfigureNetworkStatic(interface_name, address, netmask, gateway)) {
                    success = false;
                    errorMsg = "Failed to configure static IP";
                }
            } else if (mode == "dhcp") {
                if (!systemServer.ConfigureNetworkDhcp(interface_name)) {
                    success = false;
                    errorMsg = "Failed to configure DHCP";
                }
            } else {
                response["code"] = 400;
                response["message"] = "Bad Request";
                response["data"] = nullptr;
                response["error"] = "Invalid network mode. Must be 'static' or 'dhcp'";
                return false;
            }
        }

        // 设置DNS服务器
        if (success && body.contains("ipv4") && body["ipv4"].contains("dns")) {
            auto dnsArray = body["ipv4"]["dns"];
            if (!dnsArray.is_array()) {
                success = false;
                errorMsg = "DNS servers must be an array";
            } else if (dnsArray.size() > 0) {
                std::string primaryDns = dnsArray[0].get<std::string>();
                std::string secondaryDns = dnsArray.size() > 1 ? dnsArray[1].get<std::string>() : "";

                if (!systemServer.ConfigureDnsServers(primaryDns, secondaryDns)) {
                    success = false;
                    errorMsg = "Failed to set DNS servers";
                }
            }
        }

        // 设置响应
        auto now = std::chrono::system_clock::now();
        auto now_time_t = std::chrono::system_clock::to_time_t(now);
        std::tm tm_now;
        gmtime_r(&now_time_t, &tm_now);
        char time_str[30];
        strftime(time_str, sizeof(time_str), "%Y-%m-%dT%H:%M:%SZ", &tm_now);

        if (success) {
            response["code"] = 200;
            response["message"] = "Network interface configuration updated successfully";

            nlohmann::json data;
            data["status"] = "success";
            data["applied_at"] = time_str;
            data["requires_reboot"] = false;

            response["data"] = data;
            response["error"] = nullptr;
        } else {
            response["code"] = 500;
            response["message"] = "Failed to apply network configuration";
            response["data"] = nullptr;
            response["error"] = errorMsg;
        }

        return success;
    } catch (const std::exception &e) {
        response["code"] = 500;
        response["message"] = "Error updating network configuration";
        response["data"] = nullptr;
        response["error"] = e.what();
        return false;
    }
}

void RegisterNetworkApiHandlers()
{
    WebServer::IHttpServer &server = WebServer::IHttpServer::GetInstance();
    server.RegisterHandler("GET", "^/v1/network/config$", HandleGetNetworkConfig);
    server.RegisterHandler("PUT", "^/v1/network/interfaces/([^/]+)$", HandleUpdateInterfaceConfig);
}

} // namespace Restful
} // namespace El